package com.yeb.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeb.server.config.security.JwtTokenUtil;
import com.yeb.server.config.security.SecurityConfig;
import com.yeb.server.mapper.AdminMapper;
import com.yeb.server.mapper.AdminRoleMapper;
import com.yeb.server.mapper.RoleMapper;
import com.yeb.server.pojo.Admin;
import com.yeb.server.pojo.AdminRole;
import com.yeb.server.pojo.Menu;
import com.yeb.server.pojo.Role;
import com.yeb.server.service.IAdminService;
import com.yeb.server.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liushizhong
 * @since 2021-09-09
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

     @Autowired
     private UserDetailsService userDetailsService; // SpringSecurity 默认使用 UserDetailsService 来实现登入流程,这里在 SecurityConfig 中被实例化
     @Autowired
     private PasswordEncoder passwordEncoder; // 密码编码器，这里在 SecurityConfig 中被实例化
     @Autowired
     private JwtTokenUtil jwtTokenUtil; // jwt token 工具类
     @Value("${jwt.tokenHead}")
     private String tokenHead;
     @Autowired
     private AdminMapper adminMapper;
     @Autowired
     private RoleMapper roleMapper;
     @Autowired
     private AdminRoleMapper adminRoleMapper;

    /**
     * 登入后返回 token
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code,HttpServletRequest request) {
        // 从 Session 中获取验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        if(StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码错误,请重新输入!");
        }
        //登录，这里走的时自定义的登录逻辑，loadUserByUsername 被重写了
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // userDetails 为空或者密码不正确
        if(userDetails == null||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确!");
        }
        //账号被禁用
        if(!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员!");
        }
        //创建登入用户认证 token UsernamePasswordAuthenticationToken 是 Authentication 接口实现类
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails,null,userDetails.getAuthorities());
        // 将登入认证信息放到 Security 全局上下文中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成 token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead); // 让前端放在其请求头里
        return RespBean.success("登入成功",tokenMap);
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username)
        .eq("enabled",true));
    }

    /**
     * 根据用户 id 获取角色列表
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    /**
     * 获取所有操作员
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        // 第一个参数为当前用户 id,从 SpringSecurity 上下文中取出
        return adminMapper.getAllAdmins(((Admin)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId(),keywords);
    }

    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        // 1.删除所有权限
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        // 2.添加权限
        Integer result = adminMapper.addAdminRole(adminId, rids);
        if(result == rids.length){
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    /**
     * 更新用户密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 新旧密码匹配
        if(encoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(encoder.encode(pass));
            int result = adminMapper.updateById(admin);
            if(1 == result){
                return RespBean.success("更新成功！");
            }
        }
        return RespBean.error("更新失败！");
    }
}
